/**
 *
 * User: 管小龙
 * Date: 2018/2/6
 * Time: 17:51
 *
 */
import * as dateUtil from "../../util/date";

class Pay {
  constructor(options) {
    this.detail = options.orderInfo; //OrderSerialId,TotalTicketPrice
    this.fn = options.fn || function() {};
    this.vm = options.vm;
    this.useDirectPay = options.useDirectPay;
    this.directWxPay = options.directWxPay || false; //小程序环境下，直接走微信支付（开关控制）
    this.pay();
  }
  payOrder(res) {
    window.wx.ready(() => {
      let data = this.detail || {};
      let vm = this.vm;
      // 存储,表示已经唤起直连支付
      vm.$local.trainUseDirectPay(data.OrderSerId, true);
      //调用支付
      window.wx.chooseWXPay({
        timestamp: res.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
        nonceStr: res.nonceStr, // 支付签名随机串，不长于 32 位
        package: res.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
        signType: res.signType || "MD5", // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
        paySign: res.paySign, // 支付签名
        success: res => {
          // 支付成功后的回调函数
          this.fn(res.errMsg == "chooseWXPay:ok");
        },
        cancel: () => {
          this.fn(false);
        }
      });
    });
  }

  miniWxPay(res) {
    this.vm.$loading && this.vm.$loading.hide();
    window.WeixinJSBridge.invoke(
      "getBrandWCPayRequest",
      {
        appId: "wx3827070276e49e30", // 公众号名称，由商户传入
        timeStamp: res.timeStamp, // 时间戳，自1970年以来的秒数
        nonceStr: res.nonceStr, // 随机串
        package: res.package,
        signType: res.signType || "MD5",
        paySign: res.paySign // 微信签名
      },
      res => {
        // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        this.fn(res.err_msg == "get_brand_wcpay_request:ok");
      }
    );
  }

  miniChat() {
    this.vm.$tcTrackEvent({
      action: "wx-h5-miniChat"
    });
    let orgin = this.vm.$env.orgin;
    //小程序支付跳转
    window.wx.miniProgram.redirectTo({
      url:
        "/page/train/webapp/incrementPay/incrementPay?orderNo=" +
        this.detail.OrderSerId +
        "&OrderId=0&userid=" +
        orgin.userId +
        "&openId=" +
        orgin.openId +
        "&n=1"
    });
  }

  //微信支付
  wxPay() {
    // mileage > 0 使用了里程
    // newUseMileage
    // DeductAmount 代金券 抵扣

    let data = this.detail || {};
    let vm = this.vm;

    // 是否直连支付
    let UseDirectPay = this.UseDirectPay;
    if (UseDirectPay == null) {
      if (
        data.mileage > 0 ||
        data.newUseMileage > 0 ||
        data.DeductAmount > 0 ||
        vm.$local.trainUseDirectPay(data.OrderSerId)
      ) {
        UseDirectPay = false;
      }
    }

    let orgin = this.vm.$env.orgin;

    //几天不见，增加了N多参数
    let param = {
      // openId，userId， platId 使用的原始的
      memberId: orgin.userId,
      platId: orgin.platId,
      openId: orgin.openId,

      VipParam: {},
      AppreciationType: 0, //增值服务类型，0-无增值产品，1-代金券（月卡），2-餐食，3-用车，4-贵宾厅，5-主动售卖餐食
      ActiveMealParam: {},
      CarParam: {},
      AppreciationTypeList: [],
      PayParam: {
        OrderNo: data.OrderSerId,
        OrderAmount: Number(data.PayPrice).toFixed(2),
        UseDirectPay,
        PayType: 0,
        PayTime: dateUtil.format(new Date(), "YYYY-MM-DD hh:mm:ss"),
        FromPlat: orgin.platId,
        AppId: "wx3827070276e49e30",
        MemberId: orgin.userId,
        OrderId: data.OrderId || 0,
        Sign: "",
        NoticeUrl: "",
        ClientIp: ""
      },
      IsMoreAppreciation: false,
      HasMileDeductible: false,
      MileParam: {},
      MealParam: {},
      ShelfParam: {}
    };
    vm.$model.train.wechatPay(param).then(res => {
      if (!res || !res.data) {
        this.fn(false);
        return;
      }
      if (this.directWxPay) {
        this.miniWxPay(res.data);
      } else {
        this.payOrder(res.data);
      }
    });
  }

  pay() {
    if (this.vm.$env.isMiniProgram && !this.directWxPay) {
      this.miniChat();
      return;
    }
    this.wxPay();
  }
}

export default Pay;
